package com.steshov.trainer.activities;

import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.steshov.trainer.R;
import com.steshov.trainer.dao.TaskDAO;
import com.steshov.trainer.model.Task;
import com.steshov.trainer.service.NotificationService;
import com.steshov.trainer.service.Player;
import com.steshov.trainer.utils.Adapters;
import com.steshov.trainer.utils.App;
import com.steshov.trainer.utils.Command;
import com.steshov.trainer.utils.DB_Utils;
import com.steshov.trainer.utils.Reservation;
import com.steshov.trainer.utils.Stress;

public class Index extends Activity {

	private Button toTasksButton;
	private Button toExerciseButton;
	private ToggleButton generateButton;
	private GridView grid;
	private TaskDAO taskDAO;
	private Timer timer = new Timer();
	private ArrayList<String> dataList = new ArrayList<String>();
	private ArrayList<Integer> idList = new ArrayList<Integer>();
	private String theme;
	public ArrayList<Task> generatedTasks = new ArrayList<Task>();
	ImageView animView;
	{
		App.taskMode = App.CREATE_TASK_MODE;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_index);
		DB_Utils.db = openOrCreateDatabase(DB_Utils.DB_NAME, MODE_PRIVATE, null);
		DB_Utils.setReady();
		theme = Reservation.get(this, "theme");
		App.generateButtonFlag = new Boolean(Reservation.get(this,
				"generateButtonFlag"));
		loadTheme(theme);
		// startService(new Intent(this,BackGroundService.class));
		taskDAO = new TaskDAO();
		toTasksButton = (Button) findViewById(R.id.button1);
		toTasksButton.setOnClickListener(Adapters.toTasksPage());
		toExerciseButton = (Button) findViewById(R.id.button2);
		toExerciseButton.setOnClickListener(Adapters.toExercisePage());
		generateButton = (ToggleButton) findViewById(R.id.toggleButton1);
		generateButton.setOnClickListener(Adapters.toglingGeneration());
		generateButton.setChecked(App.generateButtonFlag);
		TextView label = (TextView) findViewById(R.id.textView2);
		registerForContextMenu(label);
		grid = (GridView) findViewById(R.id.gridView1);
		grid.setNumColumns(App.colNum);
		Player.getMusicList(getContentResolver());
		animView = (ImageView) findViewById(R.id.imageView1);
		animView.setBackgroundResource(R.drawable.animation);

		grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v, int index,
					long id) {
				String command = ((TextView) v).getText().toString();
				if (App.commandContains(command)) {
					switch (Command.valueOf(command)) {
					case Delete:
						deleteTask(App.getRowNumberByIndex(index));
						break;
					case Edit:
						editTask(index);
						break;
					}
				}
			}

		});

		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				runOnUiThread(new Runnable() {
					public void run() {
						initGrid();
					}
				});
			}
		}, 0, 1000);

		Button photoButton = (Button) this.findViewById(R.id.button3);
		photoButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent cameraIntent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(cameraIntent, 1888);
			}
		});

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1888 && resultCode == RESULT_OK) {
			Bitmap photo = (Bitmap) data.getExtras().get("data");
			LinearLayout back = (LinearLayout) findViewById(R.layout.bglayout);
			back.setBackgroundDrawable(new BitmapDrawable(photo));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		signal();
		getMenuInflater().inflate(R.menu.activity_index, menu);
		App.initOptMenu(menu);
		return true;
	}

	private void signal() {
		MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.ding);
		mPlayer.start();
	}

	private void initGrid() {
		ArrayList<Task> tasks = taskDAO.getTasks(this);
		tasks.addAll(generatedTasks);
		dataList.clear();
		idList.clear();
		for (Task task : tasks) {
			String timeleft = App.convertToTimeLeft(task.getTime());
			idList.add(task.getId());
			dataList.add(task.getExercise());
			dataList.add(String.valueOf(task.getAmount()));
			dataList.add(timeleft);
			dataList.add(Command.Edit.toString());
			dataList.add(Command.Delete.toString());
			Log.i("i", task.getExercise() + ": " + timeleft);
			if (timeleft.equals("0:0:50")) {
				startService(new Intent(this, NotificationService.class)
						.putExtra("exercise", task.getExercise()).putExtra(
								"amount", task.getAmount()));
				if (Reservation.get(this, "state").equals("success")) {
					exerciseDoneDialog().show();
				}

			}
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.grid_layout,
				(String[]) dataList.toArray(new String[0]));

		grid.setAdapter(adapter);
	}

	private void editTask(int index) {
		int rowNumber = App.getRowNumberByIndex(index);
		long timeInMilis;
		String timeString = dataList.get(index - 1);
		if (!timeString.equals(App.Finished)) {
			timeInMilis = new Date().getTime()
					+ App.fromTimeStringToMilis(timeString);
		} else {
			timeInMilis = new Date().getTime();
		}

		TaskActivity.editingTask = new Task(idList.get(rowNumber),
				dataList.get(index - 3), Integer.parseInt(dataList
						.get(index - 2)), timeInMilis);
		App.taskMode = App.EDIT_TASK_MODE;
		Intent myIntent = new Intent(this, TaskActivity.class);
		startActivityForResult(myIntent, 0);
	}

	private void deleteTask(final int rowIndex) {
		AlertDialog.Builder deleteTaskAlert = new AlertDialog.Builder(this);
		deleteTaskAlert.setTitle("Confirm");
		deleteTaskAlert.setMessage("Are you sure?");
		deleteTaskAlert.setPositiveButton("Delete",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						taskDAO.removeTask(Index.this, idList.get(rowIndex));
						dialog.dismiss();
					}
				});
		deleteTaskAlert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

		deleteTaskAlert.show();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		((AnimationDrawable) animView.getBackground()).start();
		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		App.onOptionsItemSelectedThing(item, this);
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		getMenuInflater().inflate(R.menu.themes, menu);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		String itemTitle = item.getTitle().toString();
		loadTheme(itemTitle);
		return super.onContextItemSelected(item);
	}

	private void loadTheme(String theme) {
		LinearLayout back = (LinearLayout) findViewById(R.layout.bglayout);
		this.theme = theme;
		if (theme.equals(Stress.YELLOW.toString())) {
			back.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.yellow_background));
		} else if (theme.equals(Stress.GREEN.toString())) {
			back.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.green_background));
		} else if (theme.equals(Stress.RED.toString())) {
			back.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.red_background));
		}
		Reservation.put(this, "theme", theme);
	}

	public Dialog exerciseDoneDialog() {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder.setTitle("Have you done the exercise?");
		alertDialogBuilder.setMessage("Did you really done the exercise?");
		alertDialogBuilder.setPositiveButton("Yes, I did",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Player.sendMessage(true);
						dialog.dismiss();
					}
				});

		alertDialogBuilder.setNegativeButton("No I didn't",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Player.sendMessage(false);
						dialog.dismiss();
					}
				});
		return alertDialogBuilder.create();
	}

	@Override
	protected void onStop() {
		Reservation.put(this, "theme", theme);
		super.onStop();
	}

	public TaskDAO getTaskDAO() {
		return taskDAO;
	}

	public String getStressLevel() {
		return theme;
	}

	public void setGeneratedTasks(ArrayList<Task> generatedTasks) {
		this.generatedTasks = generatedTasks;
	}

	static public Index getContext() {
		return getContext();
	}

}
